package com.iwunu.gateway.service;


import java.util.HashMap;
import java.util.Map;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.iwunu.gateway.config.MqttCofigBean;


@Component
public class LockMqttServerService implements ApplicationRunner{
	private static Logger logger= LoggerFactory.getLogger(LockMqttServerService.class);
	private static MqttClient client;
	private static MqttTopic mqttTopic;
	/**
     * MQTT连接属性配置对象
     */
    @Autowired
    public MqttCofigBean mqttCofigBean;
    /**
     * 初始化参数配置
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("初始化启动MQTT连接");
        this.connect();
    }


    /**
     *  用来连接服务器
     */
    private void connect() throws Exception{
        client = new MqttClient(mqttCofigBean.getHostUrl(),mqttCofigBean.getClientId(), new MemoryPersistence());
        //订阅消息
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(mqttCofigBean.getUsername());
        options.setPassword(mqttCofigBean.getPassword().toCharArray());
        //是否清除session
        options.setCleanSession(false);
        // 设置超时时间
        options.setConnectionTimeout(mqttCofigBean.getCompletionTimeout());
        // 设置会话心跳时间
        options.setKeepAliveInterval(mqttCofigBean.getKeepalive());
        try {
            client.connect(options);
            client.subscribe(mqttCofigBean.getDefaultTopic().split(","));
            logger.info("MQTT连接成功:"+mqttCofigBean.getClientId()+":"+client);
        } catch (Exception e) {
            logger.error("MQTT连接异常："+e);
        }
    }


    /**
     * 重连
     * @throws Exception
     */
    public void reConnect() throws Exception {
        if(null != client) {
            this.connect();
        }
    }
    public void publish( String queueName, String msg) {
		MqttMessage mqttMsg = new MqttMessage();
		mqttMsg.setPayload(msg.getBytes());
		mqttMsg.setQos(0);
		mqttMsg.setRetained(false);
		try {
			client.publish(queueName, mqttMsg);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e.getMessage(), e);
		}
	}

    public MqttClient getClient() {
        return client;
    }

    public void setClient(MqttClient client) {
        this.client = client;
    }

    public MqttTopic getMqttTopic() {
        return mqttTopic;
    }

    public void setMqttTopic(MqttTopic mqttTopic) {
        this.mqttTopic = mqttTopic;
    }
}
